//
//  CircularReferenceViewController.m
//  GCD
//
//  Created by fangyuan ding on 2022/2/18.
//  Copyright © 2022 fangyuan ding. All rights reserved.
//

#import "CircularReferenceViewController.h"

typedef void(^MyBlock)(int a);

typedef void(^MySecondBlock)(CircularReferenceViewController *vc);

@interface CircularReferenceViewController ()

@property (nonatomic,copy) MyBlock myblock;

@property (nonatomic,copy) MySecondBlock mySecondblock;

@end

@implementation CircularReferenceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //会引起循环引用
//    CircularReferenceViewController *weakSelf = self;
//       self.myblock = ^(int a) {
//           [self doSomething];
//       };
    
    
    
    //使用__weak定义一个弱引用的self临时变量，去掉强引用，这也是最常用的一种方法
//    __weak typeof(self) weakSelf = self;
//        self.myblock = ^(int a) {
//            [weakSelf doSomething];
//        };
    
    
    //同样是声明一个临时self的变量，但是要记得在block里使用完这个临时变量时，把它置空，而且还要调用这个block：
//    __block CircularReferenceViewController *weakSelf = self;
//        self.myblock = ^(int a) {
//            [weakSelf doSomething];
//            weakSelf = nil;
//        };
//        self.myblock(1);
    

   
  
     //这个地方我们需要做一些改造，block重新定义一下：

//    self.mySecondblock = ^(CircularReferenceViewController *vc) {
//            [vc doSomething];
//        };
//        self.mySecondblock(self);
    
    
    
    //比如说self在block里延迟使用了，但是block走完之后weakSelf就不存在了，所以doSomething也就没有响应：
//    __weak typeof(self) weakSelf = self;
//        self.myblock = ^(int a) {
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [weakSelf doSomething];
//            });
//        };
    
    
    //Block执行过程中self对象被释放，用__strong修饰self，记得得调用了Block才起作用：
//    __weak typeof(self) weakSelf = self;
//        self.myblock = ^(int a) {
//            __strong typeof(self) strongSelf = weakSelf;
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [strongSelf doSomething];
//            });
//        };
//        self.myblock(1);
   
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)doSomething
{
    NSLog(@"%s",__func__);
}

-(void)dealloc
{
    NSLog(@"%s",__func__);
}

@end
